//! # RustCloud CLI Tool
//!
//! 一个功能强大的命令行工具，用于 RustCloud 微服务项目的脚手架生成、代码生成、部署和调试。

use clap::{Parser, Subcommand};
use std::process;
use tracing::{error, info};

mod commands;
mod config;
mod error;
mod templates;
mod utils;
mod generate_helpers;

use commands::*;
use config::CliConfig;
use error::{CliError, CliResult};

/// RustCloud CLI - 微服务开发工具
#[derive(Parser)]
#[command(name = "rustcloud")]
#[command(about = "RustCloud 微服务框架命令行工具")]
#[command(version = env!("CARGO_PKG_VERSION"))]
#[command(author = "RustCloud Team")]
struct Cli {
    /// 启用调试模式
    #[arg(short, long, global = true)]
    debug: bool,

    /// 配置文件路径
    #[arg(short, long, global = true)]
    config: Option<String>,

    /// 子命令
    #[command(subcommand)]
    command: Commands,
}

/// 支持的命令
#[derive(Subcommand)]
enum Commands {
    /// 初始化新的 RustCloud 项目
    Init(init::InitArgs),
    
    /// 生成代码（服务、模型、配置等）
    Generate(generate::GenerateArgs),
    
    /// 部署服务到目标环境
    Deploy(deploy::DeployArgs),
    
    /// 调试运行中的服务
    Debug(debug::DebugArgs),
    
    /// 管理项目配置
    Config(config_cmd::ConfigArgs),
    
    /// 显示项目信息和状态
    Status(status::StatusArgs),
    
    /// 开发服务器（热重载）
    Dev(dev::DevArgs),
    
    /// 构建项目
    Build(build::BuildArgs),
    
    /// 测试项目
    Test(test::TestArgs),
    
    /// 管理插件
    Plugin(plugin::PluginArgs),
}

#[tokio::main]
async fn main() {
    // 解析命令行参数
    let cli = Cli::parse();

    // 初始化日志
    init_logging(cli.debug);

    // 加载配置
    let config = match load_config(cli.config.as_deref()).await {
        Ok(config) => config,
        Err(e) => {
            error!("加载配置失败: {}", e);
            process::exit(1);
        }
    };

    // 执行命令
    if let Err(e) = run_command(cli.command, config).await {
        error!("命令执行失败: {}", e);
        process::exit(1);
    }
}

/// 初始化日志系统
fn init_logging(debug: bool) {
    let level = if debug {
        tracing::Level::DEBUG
    } else {
        tracing::Level::INFO
    };

    tracing_subscriber::fmt()
        .with_max_level(level)
        .with_target(false)
        .with_thread_ids(false)
        .with_file(false)
        .with_line_number(false)
        .init();

    info!("🚀 RustCloud CLI v{} 启动", env!("CARGO_PKG_VERSION"));
}

/// 加载配置文件
async fn load_config(config_path: Option<&str>) -> CliResult<CliConfig> {
    match config_path {
        Some(path) => CliConfig::from_file(path).await,
        None => CliConfig::load_default().await,
    }
}

/// 执行具体命令
async fn run_command(command: Commands, config: CliConfig) -> CliResult<()> {
    match command {
        Commands::Init(args) => init::execute(args, config).await,
        Commands::Generate(args) => generate::execute(args, config).await,
        Commands::Deploy(args) => deploy::execute(args, config).await,
        Commands::Debug(args) => debug::execute(args, config).await,
        Commands::Config(args) => config_cmd::execute(args, config).await,
        Commands::Status(args) => status::execute(args, config).await,
        Commands::Dev(args) => dev::execute(args, config).await,
        Commands::Build(args) => build::execute(args, config).await,
        Commands::Test(args) => test::execute(args, config).await,
        Commands::Plugin(args) => plugin::execute(args, config).await,
    }
}